package com.controller;

import com.baomidou.mybatisplus.extension.service.IService;
import com.entity.base.BaseEntity;
import com.entity.base.Result;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

@Controller
public abstract class BaseController<T extends BaseEntity,M extends IService<T>> {
    @Autowired
    protected M manager;

    final Logger logger = LogManager.getLogger(this.getClass().getName());


    @PostMapping("/findOne")
    public Result findOne(@RequestBody String id){
        T t = manager.getById(Long.valueOf(id));
        return Result.success(t);
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody String id) {
        manager.removeById(Long.valueOf(id));
        return Result.success();
    }

    @GetMapping("/deleteAll")
    public Result delete() {
        manager.remove(null);
        return Result.success();
    }


    @PostMapping("/deleteMessages")
    public Result deleteMessages(@RequestBody List<T> t) {
        for(int i =0;i<t.size();i++)
            manager.removeById(t.get(i).getId());
        return Result.success();
    }

    @PostMapping("/update")
    public Result update(@RequestBody T t) {
        manager.updateById(t);
        return Result.success();

    }
    @PostMapping("/save")
    public Result save(@RequestBody T t) {
        List<T> list = manager.list(null);
        for (int i =0;i<list.size();i++){
            if(t.getId()==list.get(i).getId()){
                return Result.error("已存在");
            }
        }
        Boolean istrue = manager.save(t);
        if (istrue)
            return Result.success();
        else return Result.error("保存失败");
    }
    @GetMapping("/findAll")
    public Result findAll() {
        List<T> list = manager.list(null);
        return Result.success(list);
    }

}
